//
//  LoginViewModel.m
//  DataStatistics
//
//  Created by Kang on 16/6/13.
//  Copyright © 2016年 YTYangK. All rights reserved.
//

#import "LoginViewModel.h"
#import "LoginModel.h"
#import "SearchViewModel.h"
#import "TabBarC.h"

#define  JSESSIONID @"JSESSIONID"
@interface LoginViewModel ()
@property (assign, nonatomic) BOOL isState; //获取状态
@end

@implementation LoginViewModel

// API职责 --负责发起请求， 不负责返回数据
#pragma mark - 登陆
+ (void) requestWithUrlForLoginIn:(id)obj  andParam:(NSDictionary *)param success:(void(^)(LoginModel * model))success failure:(void(^)(NSString * error))failure {
     __weak typeof(self) weakSelf = self;
    [[UtilToolsClss getUtilTools] addDoLoading];
   
    [NetRequestClss requestWithUrl:@"login/loginSubmit.asp" requestWithParameters:param method:NetMethodPOST returnSuccess:^(id objs, int status, NSString *mag) {
       [[UtilToolsClss getUtilTools] removeDoLoading];
        [weakSelf obtainHTTPCookie];
        
        NSString *errorStr = @"";
        int loginResultCode = [objs[@"body"][@"loginResult"] intValue];
        [NSUD setObject:objs[@"body"][@"roleCode"] forKey:@"roleCode"];
        [NSUD setObject:objs[@"body"][@"userName"] forKey:@"userName"];
        
        NSLog(@"登录ID ==============  %d",loginResultCode);
        
        if (loginResultCode == 8) {
            LoginModel *list = [LoginModel mj_objectWithKeyValues:objs[@"body"]];
            [weakSelf obtainHeadImage:list.headImage];
            
            NSLog(@"返回body数据 ============ %@",objs[@"body"]);
            if (objs) {
                success(list);
                return;
            }
            
            
        }else if (loginResultCode == 0) {
            errorStr = NSLocalizedString(@"LVCP1", @"请输入账号密码");
        }else if (loginResultCode == 1) {
            errorStr = NSLocalizedString(@"LM1", @"账户不存在,请联系客服!");
        }else if (loginResultCode == 2) {
            errorStr = NSLocalizedString(@"LM2", @"输入的账号或密码错误，请重新输入！");
        }else if (loginResultCode == 3 || loginResultCode == 4) {
            errorStr =  NSLocalizedString(@"LM3", @"服务器繁忙，请稍后再尝试！");
        }else if (loginResultCode == 5){
            errorStr = NSLocalizedString(@"LM4",@"该账户没有权限,请联系客服！");
        }else if (loginResultCode == 6){
            errorStr = NSLocalizedString(@"LM5",@"该账户已停止使用,请联系客服！");
        }
        failure(errorStr);
    } returnError:^(NSString *err) {
        [[UtilToolsClss getUtilTools] removeDoLoading];
        [MBProgressHUD showError:err];
    }];
    
}


#pragma mark - 验证手机注册情况
+ (void)requestWithUrlForRegisteredAccountSign:(NSString *)sign andParam:(NSDictionary *)param success:(void (^)(id model))success failure:(void (^)(NSString *err))failure {
    [[UtilToolsClss getUtilTools] addDoLoading];
    [NetRequestClss requestWithUrl:@"userInfo/phoneVerify.asp" requestWithParameters:param method:NetMethodPOST returnSuccess:^(id objs, int status, NSString *mag) {
        [[UtilToolsClss getUtilTools] removeDoLoading];
        
        NSString *regisStr = [objs[@"body"] objectForKey:@"result"];
        int regisInt  = [regisStr intValue];
        if (regisInt == 1) {
            if ([sign isEqualToString:@"Registered"]) {
                success(regisStr);
            }else {
                failure(NSLocalizedString(@"RAVCP4", nil));
            }
        }else if(regisInt == 2) {
            if ([sign isEqualToString:@"Forget"]) {
                success(regisStr);
            }else {
                failure(NSLocalizedString(@"RAVCP1", nil));
            }
        }else {
            failure(NSLocalizedString(@"RAVCP2", nil));
        }
        
        
    } returnError:^(NSString *err) {
        [[UtilToolsClss getUtilTools] removeDoLoading];
    }];
}

#pragma mark - 校验手机短信
+ (void)requestWithUrlForVerification:(id)obj andParam:(NSDictionary *)param success:(void(^)(id model))success failure:(void(^)(NSString *err))failure {
    [[UtilToolsClss getUtilTools] addDoLoading];
    
    [NetRequestClss requestWithUrl:@"userInfo/phoneSmsVerify.asp" requestWithParameters:param method:NetMethodPOST returnSuccess:^(id objs, int status, NSString *mag) {
        [[UtilToolsClss getUtilTools] removeDoLoading];
        
        int errorNam = [[[objs objectForKey:@"body"] objectForKey:@"error"] intValue];
        NSString *resultStr = [[objs objectForKey:@"body"] objectForKey:@"result"];
        int result   = [resultStr intValue];
        if (result == 1) {
            success(resultStr);
        }else {
            NSString *messageStr = [NSString stringWithFormat:@"%ddescription",errorNam];
            failure(NSLocalizedString(messageStr, nil));
        }
        
    } returnError:^(NSString *err) {
        [[UtilToolsClss getUtilTools] removeDoLoading];
        failure(NSLocalizedString(@"400description", nil));
    }];
    
    
}

#pragma  mark - 重新设置密码
+ (void)requestWithUrlForForgetPassword:(id)obj andParam:(NSDictionary *)param success:(void(^)(id model))success failure:(void(^)(NSString *err))failure {
    [[UtilToolsClss getUtilTools] addDoLoading];
    [NetRequestClss requestWithUrl:@"userInfo/userReset.asp" requestWithParameters:param method:NetMethodPOST returnSuccess:^(id objs, int status, NSString *mag) {
        [[UtilToolsClss getUtilTools] removeDoLoading];
        
        NSString * resultStr = [[objs objectForKey:@"body"] objectForKey:@"result"];
        int result = [resultStr intValue];
        if (result == 1) {
            success(resultStr);
        }else {
            failure(NSLocalizedString(@"FPVCP3", nil));
        }
        
    } returnError:^(NSString *err) {
        [[UtilToolsClss getUtilTools] removeDoLoading];
    }];

}



// 保存 cooke
+ (void)obtainHTTPCookie {
    NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    NSData *cookiesData = [NSKeyedArchiver archivedDataWithRootObject:[cookieStorage cookies]];
    [NSUD setValue:cookiesData forKey:@"allCookie"];
    
    
    for (NSHTTPCookie *cookie in [cookieStorage cookies]) {
        if ([cookie.name isEqualToString:JSESSIONID]) {
          NSLog(@"%@",cookie.name);
            [NSUD setObject:cookie.value forKey:TOKEN];
            break;
        }
    }
}

// 设置头像
+ (void)obtainHeadImage:(NSString *)imagerStr {

    if (imagerStr !=  nil || ![imagerStr isEqualToString:@""]) {
        NSURL *url = [NSURL URLWithString:[GET_HEND_IMAGE_IP stringByAppendingString:imagerStr]];
        
        dispatch_queue_t imagaQueue = dispatch_queue_create("headImageQueue", NULL);
        dispatch_async(imagaQueue, ^{
            if ([NSData dataWithContentsOfURL:url options:0 error:NULL]) {
               NSData *imageData = [NSData dataWithContentsOfURL:url options:0 error:NULL];
                if (imageData) {
                    [[NSUserDefaults standardUserDefaults] setObject:imageData forKey:@"headImage"];
                }
            }
        });
    }
}


/** 跳转页面 */
+ (void)loginWithViewController:(UIViewController *)viewController {
       
        [[NSUserDefaults standardUserDefaults]setObject:@"YES" forKey:@"isAutomaticLogin"];
        
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        TabBarC *tab = [storyboard instantiateInitialViewController];
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        [UIApplication sharedApplication].statusBarHidden = NO;
        window.rootViewController = tab;
}

@end
